#!/bin/bash
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

# 对比两个文件的md5是否相等
checkMd5() {
    # 取得两个文件
    file1=$1
    file2=$2

    # 计算两个文件的md5
    which "md5sum" > /dev/null
    if [ $? -eq 0 ]
    then
        file1_md5=`md5sum ${file1} | awk '{print $1}'`
        file2_md5=`md5sum ${file2} | awk '{print $1}'`
    else
        file1_md5=`md5 ${file1} | awk '{print $1}'`
        file2_md5=`md5 ${file2} | awk '{print $1}'`
    fi


    # 对比两个文件的md5值
    if [[ "$file1_md5" == "$file2_md5" ]]
    then
        # 如果两个文件的md5值相等，则直接退出0,表示成功
        return 0
    fi

    # 返回code表示md5不一样
    return 1
}


# 根据文件目录找两个文件
git_dir=`git rev-parse --git-dir`
app_root=$(dirname "$git_dir")
file1="${app_root}/.env"
file2="${app_root}/.env.example"

# 校验md5
checkMd5 ${file1} ${file2}
check_status=$?

# 如果两个文件完全相同，则直接退出成功
if [ $check_status -eq 0 ]; then
    echo "check .env file changes: no changes, success."
    exit 0
fi

echo ".env file changed, start to copy and add."

# 如果两个文件不同，复制文件
cp ${file1} ${file2}

# 再次校验md5
checkMd5 ${file1} ${file2}
check_status=$?

# 如果两个文件完全相同
if [ $check_status -eq 0 ]; then
    # 添加文件到git
    git add ${file2}

    echo ".env file copy and add success."

    # 直接退出成功
    exit 0
fi

# 复制文件后，md5仍然不同，退出表示错误
echo ".env file copy or add failed, see pre-commit: .env=>.env.example for more information."
exit 1








